﻿/*
 *  phpMyAdminVersion.cs
 *
 *  Copyright (C) 2008 Dreamlusion <dreamlusion@gmail.com>
 *
 *      This program is free software; you can redistribute it and/or
 *      modify it under the terms of the GNU General Public License version
 *      2 as published by the Free Software Foundation.
 *
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;

namespace phpMyAdminToolkit.Common
{
	sealed class phpMyAdminVersion
	{
		public static phpMyAdminVersion Create(string value)
		{
			if (string.IsNullOrEmpty(value))
				throw new ArgumentException("A value is required.", "value");

			string[] parts = value.Split('.');

			if (parts.Length < 2)
				throw new ArgumentException("At least two (2) numeric identifiers are required for a valid phpMyAdmin version string.", "value");

			// Keep only the first 4 numeric identifiers.
			int[] iparts = new int[4];
			int i = 0;
			while (i < parts.Length && i < iparts.Length && int.TryParse(parts[i], out iparts[i]))
				i++;

			return new phpMyAdminVersion()
			{
				Value = value,
				Major = iparts[0],
				Minor = iparts[1],
				Build = iparts[2],
				Revision = iparts[3],
			};
		}

		public string Value { get; private set; }
		public int Major { get; private set; }
		public int Minor { get; private set; }
		public int Build { get; private set; }
		public int Revision { get; private set; }

		#region Overrides
		public override bool Equals(object obj)
		{
			return (obj is phpMyAdminVersion) ? Value.Equals((obj as phpMyAdminVersion).Value) : false;
		}

		public override int GetHashCode()
		{
			return Value.GetHashCode();
		}
		#endregion

		#region Operator Overloading
		public static bool operator ==(phpMyAdminVersion x, phpMyAdminVersion y)
		{
			try
			{
				return x.Value == y.Value;
			}
			catch
			{
				// x or y may be null.
				return false;
			}
		}

		public static bool operator !=(phpMyAdminVersion x, phpMyAdminVersion y)
		{
			return !(x == y);
		}

		public static bool operator >(phpMyAdminVersion x, phpMyAdminVersion y)
		{
			if (x.Major != y.Major)
				return x.Major > y.Major;

			if (x.Minor != y.Minor)
				return x.Minor > y.Minor;

			if (x.Build != y.Build)
				return x.Build > y.Build;

			if (x.Revision != y.Revision)
				return x.Revision > y.Revision;

			throw new InvalidOperationException();
		}

		public static bool operator <(phpMyAdminVersion x, phpMyAdminVersion y)
		{
			return !(x > y);
		}

		public static bool operator <=(phpMyAdminVersion x, phpMyAdminVersion y)
		{
			return (x == y) ? true : x < y;
		}

		public static bool operator >=(phpMyAdminVersion x, phpMyAdminVersion y)
		{
			return (x == y) ? true : x > y;
		}
		#endregion
	}
}
